package main

import (
	"irisfarm/app/commons"
	"irisfarm/app/core/config"
	"irisfarm/app/core/db"
	"irisfarm/app/core/log"
	"irisfarm/app/middlewares"
	"irisfarm/routes"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/spf13/viper"
)

func init() {
	// 初始化配置文件 多个配置文件使用,隔开
	config.New("app", "cors", "database", "iris")

	// 初始化应用日志
	log.NewAppLog()

	// 初始化数据库
	db.New()

	// 初始化mongodb
	//db.NewMongo()

	// 初始化redis
	db.NewRedis()
}

func main() {
	// 运行日志文件
	runLogFile := log.RunLogFile()
	defer runLogFile.Close()

	app := iris.New()

	// 加载recover
	app.Use(recover.New())

	// 追加运行日志文件
	app.Logger().SetLevel(viper.GetString("DebugLevel")).AddOutput(runLogFile)

	// 加载运行日志
	app.Use(logger.New())

	// 加载中间件
	app.Use(middlewares.NewCorsMiddleware)
	middlewares.NewJwtMiddleware()

	// 通用错误处理
	commons.ErrorHandle(app)

	// 加载路由
	routes.ApiRoutes(app)
	routes.TestRoutes(app)

	// 运行iris
	appRun(app)
}

func appRun(app *iris.Application) {
	ssl := viper.GetBool("ssl.enable")
	if ssl {
		address := viper.GetString("http.host") + ":443"
		_ = app.Run(
			iris.TLS(
				address,
				viper.GetString("ssl_crt"),
				viper.GetString("ssl_key"),
			),
			iris.WithoutServerError(iris.ErrServerClosed),
			iris.WithConfiguration(iris.YAML("./configs/iris.yml")),
		)
	} else {
		address := viper.GetString("http.host") + ":" + viper.GetString("http.port")
		_ = app.Run(
			iris.Addr(address),
			iris.WithoutServerError(iris.ErrServerClosed),
			iris.WithConfiguration(iris.YAML("./configs/iris.yml")),
		)
	}
}
